import React, { useEffect, useRef, useState } from 'react';
import { Button, Input, Row, Col, List, Tooltip, Tag, Modal, message, Card, theme } from 'antd';
import { DeleteOutlined, ExclamationCircleOutlined, PlusOutlined } from '@ant-design/icons';
import { getRichTextArticleTitleCategoryPrefix } from "common/utils/utils";
import { ArticleNormalCategory, ArticleStatus, articleStatus, articleStatusColor } from "common/utils/data";
import { useDebounceFn, useRequest } from "ahooks";
import { articleV1ControllerDestroyMine, articleV1ControllerIndexMine } from "@/services/auto/article";
import ScrollPageList, { PageListRef } from "@/components/ScrollPageList";
import { GetScrollPageParam } from "common/interface";
import { css } from "@emotion/react";
import cs from 'classnames';

export default function LeftSider(props) {
  const {
    setDrawerVisible,
    activeArticleUuid,
    setActiveArticleUuid,
    refreshList,
  } = props;

  const {token} = theme.useToken();

  const [filter,setFilter] = useState<GetScrollPageParam<API.ArticleV1ControllerIndexMineParams>>({
    title: undefined,
  });

  const scrollPageListRef = useRef<PageListRef<API.ArticleIndexMineResult>>(null);

  useEffect(()=>{
    refreshList.current = scrollPageListRef.current?.refresh;
  },[])

  const {run: deleteArticlesRun} = useRequest(articleV1ControllerDestroyMine,{
    manual: true,
    onSuccess: (_,[req])=>{
      message.success({
        content: '删除成功',
      });
      scrollPageListRef.current?.mutate(origin=>{
        return origin.filter(item=>item.uuid !== req?.uuid);
      });
      if(req?.uuid === activeArticleUuid){
        setActiveArticleUuid(null);
      }
    }
  })

  const scrollContainerRef = useRef<HTMLDivElement>(null);

  const {run: setTitleDebounce} = useDebounceFn((val)=>{
    setFilter(origin=>{
      return {
        ...origin,
        title: val,
      }
    })
  }, {
    wait: 500,
  })

  return (
    <Card className="h-full" classNames={{body: 'h-full px-0'}} bordered={false}>
      <div className={`h-full flex flex-col`}>
        <div className={'mb-[8px] px-[24px]'}>
          <Row gutter={16}>
            <Col flex="auto">
              <Input
                allowClear
                placeholder="输入文章标题进行搜索"
                onChange={(e)=>{
                  setTitleDebounce(e.target.value);
                }}
              />
            </Col>
            <Col flex="100px">
              <Button
                type="primary"
                onClick={() => {
                  setActiveArticleUuid(null);
                  setDrawerVisible(true);
                }}
              >
                <PlusOutlined /> 创建文章
              </Button>
            </Col>
          </Row>
        </div>
        <div className="flex-1 min-h-0">
          <div className="h-full overflow-auto" ref={scrollContainerRef}>
            <ScrollPageList
              ref={scrollPageListRef}
              param={filter}
              service={articleV1ControllerIndexMine}
              getScrollableTarget={()=>scrollContainerRef.current!}
              order={{
              orderBy: 'updateTime',
              direction: 'DESC',
            }}>
              {(data)=>{
                return <List
                  dataSource={data}
                  renderItem={item => (
                    <List.Item
                      key={item.uuid}
                      className={cs('cursor-pointer', {
                        ['active']: activeArticleUuid === item.uuid
                      })}
                      css={css`
                        position: relative;
                        padding-right: 24px !important;
                        padding-left: 24px !important;
                        &.active, &:hover{
                          background-color: #f5f5f5;
                        }
                        &.active{
                          &::before {
                            content: '';
                            position: absolute;
                            left: 0;
                            top: 0;
                            bottom: 0;
                            width: 4px;
                            background: ${token.colorPrimary};
                          }
                        }
                        .ant-list-item-action{
                          margin-left: 16px !important;
                        }
                      `}
                      actions={[
                        <DeleteOutlined
                          style={{ fontSize: '16px', transform: 'translateY(2px)' }}
                          onClick={e => {
                            e.stopPropagation();
                            Modal.confirm({
                              icon: <ExclamationCircleOutlined />,
                              type: 'error',
                              title: '请确认该操作',
                              content: `确认删除《${item.title}》吗？此操作无法恢复`,
                              onOk: ()=>{
                                return deleteArticlesRun({uuid: item.uuid});
                              }
                            })
                          }}
                        />,
                      ]}
                      onClick={() => {
                        setActiveArticleUuid(item.uuid);
                      }}
                    >
                      <div className="flex items-center flex-1 min-w-0">
                        <Tag color={articleStatusColor[item.status as ArticleStatus]} style={{
                          width: 60,
                          textAlign: 'center'
                        }}>
                          {articleStatus[item.status as ArticleStatus]}
                        </Tag>
                        <Tooltip placement="top" title={item.title}>
                          <div className="truncate flex-1 min-w-0">
                            {item.categories.map(it=>{
                              return getRichTextArticleTitleCategoryPrefix(it as ArticleNormalCategory)
                            }).join('')} {item.title}
                          </div>
                        </Tooltip>
                      </div>
                    </List.Item>
                  )}
                />
              }}
            </ScrollPageList>
          </div>
        </div>
      </div>
    </Card>
  );
};
